package com.cfweb.controller.app;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.cfweb.api.ApplicationApi;
import com.cfweb.api.OrgApi;
import com.cfweb.api.UserApi;
import com.cfweb.controller.LoginHandler;
import com.cfweb.dao.AppLogConfigMapper;
import com.cfweb.dao.AppLogPatternsMapper;
import com.cfweb.dao.AppTemplateMapper;
import com.cfweb.dao.CfAppMapper;
import com.cfweb.dao.CfEnvironmentMapper;
import com.cfweb.dao.CfServiceInstanceMapper;
import com.cfweb.dao.CfUserMapper;
import com.cfweb.dao.LogPatternMapper;
import com.cfweb.dao.PatternFieldMapper;
import com.cfweb.domain.AppLogConfigExample;
import com.cfweb.domain.AppLogPatterns;
import com.cfweb.domain.AppLogPatternsExample;
import com.cfweb.domain.AppTemplate;
import com.cfweb.domain.AppWithOrg;
import com.cfweb.domain.AppWithTpl;
import com.cfweb.domain.CfApp;
import com.cfweb.domain.CfAppExample;
import com.cfweb.domain.CfAppExternal;
import com.cfweb.domain.LogPattern;
import com.cfweb.domain.LogPatternExample;
import com.cfweb.domain.PatternField;
import com.cfweb.domain.PatternFieldExample;
import com.cfweb.enumration.InstanceState;
import com.cfweb.enumration.ServiceImageEnum;
import com.cfweb.form.UploadAppForm;
import com.cfweb.lognode.client.LognodeClient;
import com.cfweb.pojo.CfServiceInstanceWithType;
import com.cfweb.util.ExtJSResponse;
import com.cfweb.util.ExtendedGrok;
import com.cfweb.util.FormUtil;
import com.cfweb.util.StringUtil;

/**
 * 
 * @author (yufangjiang) Dec 2, 2014
 */
@Service
@Path("/app")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class AppManagement {

	/**
	 * Logger
	 */
	private Logger logger = Logger.getLogger(AppTemplate.class);

	/**
	 * ClassLoader
	 */
	private ClassLoader classLoader = this.getClass().getClassLoader();

	/**
	 * session
	 */
	@Autowired
	private HttpSession session;

	/**
	 * appMapper
	 */
	@Autowired
	private CfAppMapper caMapper;

	/**
	 * appTemplateMapper
	 */
	@Autowired
	private AppTemplateMapper atlMapper;

	/**
	 * environmentMapper
	 */
	@Autowired
	private CfEnvironmentMapper ceMapper;

	/**
	 * logPatternMapper
	 */
	@Autowired
	private LogPatternMapper lpMapper;

	/**
	 * appLogPatternsMapper
	 */
	@Autowired
	private AppLogPatternsMapper alpMapper;

	/**
	 * appLogConfigMapper
	 */
	@Autowired
	private AppLogConfigMapper alcMapper;

	/**
	 * patternFieldMapper
	 */
	@Autowired
	private PatternFieldMapper patternFieldMapper;

	/**
	 * userMapper
	 */
	@Autowired
	private CfUserMapper cuMapper;

	/**
	 * serviceInstanceMapper
	 */
	@Autowired
	private CfServiceInstanceMapper serviceInstanceMapper;

	@Autowired
	private LogManagement lm;

	@Autowired
	private LognodeClient lognodeClient;

	/**
	 * get all of applications
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Path("/listall")
	@GET
	public ExtJSResponse listall() throws Exception {
		List<AppWithOrg> result = new ArrayList<AppWithOrg>();
		List<AppWithTpl> listRes = new ArrayList<AppWithTpl>();
		List<Map<String, Object>> cList = ApplicationApi.getAllApplications(session);
		List<Map<String, Object>> orgs = OrgApi.list_orgs(session);

		if (cList != null) {
			List<CfAppExternal> cfAppList = caMapper.getCfApps();
			Map<String, CfAppExternal> nameCfappMap = new HashMap<String, CfAppExternal>();
			for (CfAppExternal cfapp : cfAppList) {
				nameCfappMap.put(cfapp.getAppName(), cfapp);
			}
			for (Map<String, Object> c : cList) {
				CfAppExternal temp = nameCfappMap.get(((Map<String, Object>) c.get("entity")).get("name"));
				if (temp != null) {
					c.put("message", lm.listApp(temp.getAppName())); // 这个先写死，等待日至接口完成
					listRes.add(new AppWithTpl(temp, c));
				}
			}
		}
		for (Map<String, Object> map : orgs) {
			String orgName = (String) map.get("name");
			List<AppWithTpl> listTemp = new ArrayList<AppWithTpl>();
			for (AppWithTpl awt : listRes) {
				if (orgName.equals(awt.getCfapp().getOrg())) {
					listTemp.add(awt);
				}
			}
			if (listTemp.size() > 0) {
				result.add(new AppWithOrg(orgName, listTemp));
			}
		}
		return ExtJSResponse.successResWithData(result);

	}

	/**
	 * get all services of an application
	 * 
	 * @param appName
	 * @return list<service>
	 */
	@Path("/services")
	@GET
	public ExtJSResponse appServices(final @QueryParam("appName") String appName) throws Exception {
		List<CfServiceInstanceWithType> services = new ArrayList<>();
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		List<String> serviceNames = ApplicationApi.getAllAppServiceName(ca.getUuid(), session);
		if (serviceNames != null && serviceNames.size() != 0) {
			services = serviceInstanceMapper.selectAppService(serviceNames);
			for (String service : serviceNames) {
				boolean addflag = true;
				for (CfServiceInstanceWithType instance : services) {
					if (instance.getServiceInstanceName().equals(service)) {
						addflag = false;
						break;
					}
				}
				if (addflag) {
					CfServiceInstanceWithType type = new CfServiceInstanceWithType();
					type.setServiceInstanceName(service);
					type.setServiceTypeImage(ServiceImageEnum.getImage(service));
					services.add(type);
				}
			}
		}
		return ExtJSResponse.successResWithData(services);
	}

	// /**
	// * get detail of service of application
	// *
	// * @param appName
	// * @param serviceName
	// * @return
	// */
	// @SuppressWarnings("unchecked")
	// @Path("/serviceDetails")
	// @GET
	// public ExtJSResponse serviceDetails(
	// final @QueryParam("appName") String appName,
	// final @QueryParam("serviceName") String serviceName) throws Exception {
	// List<CfServiceInstanceWithType> services = new ArrayList<>();
	// List<String> serviceNames = new ArrayList<>();
	// CfAppExample caEx = new CfAppExample();
	// caEx.createCriteria().andAppNameEqualTo(appName);
	// CfApp ca = caMapper.selectByExample(caEx).get(0);
	// serviceNames.add(serviceName);
	// if (serviceNames != null && serviceNames.size() != 0) {
	// String paraString =ApplicationApi.getAppFile(ca.getUuid(), 0,
	// "logs/env.log",session);
	// String[] paras = paraString.split(System.lineSeparator());
	// Map<String, Object> vcapSerInfo = null;
	// for (String para : paras) {
	// if (para.startsWith("VCAP_SERVICES")) {
	// String[] temp = para.split("=",2);
	// vcapSerInfo = JsonUtil.convertJsonToMap(temp[1]);
	// break;
	// }
	// }
	// // oracle-database-service
	// Map<String, Object> name2info = new HashMap<String, Object>();
	// if (vcapSerInfo != null) {
	// vcapSerInfo = (LinkedHashMap<String, Object>) vcapSerInfo;
	// for (Entry<String, Object> entry : vcapSerInfo.entrySet()) {
	// ArrayList<Map<String, Object>> o = (ArrayList<Map<String, Object>>) entry
	// .getValue();
	// if (o.size() == 1) {
	// name2info.put((String) o.get(0).get("name"),
	// (Object) o.get(0));
	// } else {
	// for (int i = 0; i < o.size(); i++) {
	// name2info.put((String) o.get(i).get("name"),
	// (Object) o.get(i));
	// }
	// }
	// }
	// }
	// services = serviceInstanceMapper.selectAppService(serviceNames);
	// for (String service : serviceNames) {
	// boolean addflag = true;
	// for (CfServiceInstanceWithType instance : services) {
	// if (instance.getServiceInstanceName().equals(service)) {
	// addflag = false;
	// if (((Object) name2info.get(instance
	// .getServiceInstanceName())) != null) {
	// instance.setDetail(((Map<String, Object>) name2info
	// .get(instance.getServiceInstanceName())));
	// }
	// break;
	// }
	// }
	// if (addflag) {
	// CfServiceInstanceWithType type = new CfServiceInstanceWithType();
	// type.setServiceInstanceName(service);
	// type.setServiceTypeImage(ServiceImageEnum.getImage(service));
	// services.add(type);
	// }
	// }
	// }
	// return ExtJSResponse.successResWithData(services);
	// }

	/**
	 * get detail of service of application
	 * 
	 * @param appName
	 * @param serviceName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Path("/serviceDetails")
	@GET
	public ExtJSResponse serviceDetailsNew(final @QueryParam("appName") String appName,
			final @QueryParam("serviceName") String serviceName) throws Exception {
		List<CfServiceInstanceWithType> services = new ArrayList<>();
		List<String> serviceNames = new ArrayList<>();
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		serviceNames.add(serviceName);
		if (serviceNames != null && serviceNames.size() != 0) {
			Map<String, Object> serviceEnv = (Map<String, Object>) ((Map<String, Object>) ApplicationApi
					.getAppSystemEnv(ca.getUuid(), session).get("system_env_json")).get("VCAP_SERVICES");
			Map<String, Object> name2info = new HashMap<String, Object>();
			for (Entry<String, Object> entry : serviceEnv.entrySet()) {
				ArrayList<Map<String, Object>> o = (ArrayList<Map<String, Object>>) entry.getValue();
				if (o.size() == 1) {
					name2info.put((String) o.get(0).get("name"), (Object) o.get(0));
				} else {
					for (int i = 0; i < o.size(); i++) {
						name2info.put((String) o.get(i).get("name"), (Object) o.get(i));
					}
				}
			}
			services = serviceInstanceMapper.selectAppService(serviceNames);
			for (String service : serviceNames) {
				boolean addflag = true;
				for (CfServiceInstanceWithType instance : services) {
					if (instance.getServiceInstanceName().equals(service)) {
						addflag = false;
						if (((Object) name2info.get(instance.getServiceInstanceName())) != null) {
							instance.setDetail(
									((Map<String, Object>) name2info.get(instance.getServiceInstanceName())));
						}
						break;
					}
				}
				if (addflag) {
					CfServiceInstanceWithType type = new CfServiceInstanceWithType();
					type.setServiceInstanceName(service);
					type.setServiceTypeImage(ServiceImageEnum.getImage(service));
					services.add(type);
				}
			}
		}
		return ExtJSResponse.successResWithData(services);
	}

	/**
	 * list apps in org and space
	 * 
	 * @param orgNames
	 * @param spaceName
	 * @return
	 * @throws Exception
	 */
	@Path("/listAtOrgSpa")
	@GET
	public ExtJSResponse listAtOrgSpa(final @QueryParam("org") String orgName,
			final @QueryParam("space") String spaceName) throws Exception {
		List<Map<String, Object>> list = null;
		list = ApplicationApi.getApplicationBySpace(session, orgName, spaceName);
		return ExtJSResponse.successResWithData(list);
	}

	/**
	 * upload application,该方法在管理员系统中不会用到
	 * 
	 * @param dataInput
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	@Path("/upload")
	@POST
	@Consumes("multipart/form-data")
	public ExtJSResponse uploadApp(MultipartFormDataInput dataInput, @Context HttpServletRequest request)
			throws Exception {
		try {
			UploadAppForm form = new UploadAppForm(dataInput);
			File file;
			if (form.isUploadExample()) {
				file = new File(request.getRealPath("/") + "war/helloworld.war");
			} else {
				file = form.getFile();
			}
			String appName = form.getAppName();
			String domain = form.getDomains();
			List<String> uri = new ArrayList<String>();
			uri.add(appName + "." + domain);
			List<String> services = form.getServices();
			List<String> patternKeys = form.getPatternKeys();
			List<String> patterns = form.getPatterns();

			String checkRes = checkPattern(patternKeys);
			if (checkRes != null && !"".equals(checkRes) && !"success".equals(checkRes)) {
				ExtJSResponse response = ExtJSResponse.errorRes();
				response.put("source", "patternExist");
				response.put("error", checkRes);
				return response;
			}

			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", form.getAppName());
			params.put("memory", Integer.valueOf(form.getMemory()));
			params.put("instances", Integer.valueOf(form.getInstances()));
			params.put("space_guid", UserApi.get_space_id(session, form.getOrgName(), form.getSpaceName()));
			params.put("buildpack", form.getBuildPack());
			params.put("disk_quota", 1024);
			if (form.getBuildPack().startsWith("clr_") || form.getBuildPack().toLowerCase().indexOf("net") != -1) {
				logger.info("choose .net app");
				params.put("stack_id", ApplicationApi.getStackUUID("windows2012", session));
			}
			String appUuid = ApplicationApi.createApplication(params, session);
			CfApp cfApp = new CfApp(appName, Integer.valueOf(form.getEnvId()), form.getOrgName(), form.getSpaceName(),
					form.getTemId(), appUuid);
			caMapper.insertSelective(cfApp);

			ApplicationApi.updateApplicationUrls(appUuid, form.getOrgName(), form.getSpaceName(), uri, session);
			ApplicationApi.uploadAppBit(cfApp, file, session);
			if (!form.isUploadExample()) {
				file.delete();
			}
			Integer appId = cfApp.getId();
			insert(form.getError(), form.getException(), patternKeys, patterns, appId);
			addOracleServiceParam(form.isOracleMapping(), form.isMysqlMapping(), form.getAppSources(),
					form.getServices(), appUuid);
			// bind service to app
			if (services != null) {
				for (String service : services) {
					if (service.startsWith("log")) {
						String msg = " get patterns [GP] appid:" + appUuid;
						lognodeClient.notify((msg.length() - 1) + msg);
					}
					ApplicationApi.bindService(appUuid, service, session);
				}
			}
			ApplicationApi.startApplication(appUuid, session);
		} catch (Exception e) {
			throw e;
		}
		return ExtJSResponse.successRes();
	}

	/**
	 * upload application,该方法在管理员系统中不会用到
	 * 
	 * @param dataInput
	 * @return
	 * @throws Exception
	 */
	@Path("/update")
	@POST
	@Consumes("multipart/form-data")
	public ExtJSResponse updateApp(MultipartFormDataInput dataInput, @Context HttpServletRequest request)
			throws Exception {
		File file = null;
		try {
			Map<String, List<InputPart>> uploadForm = dataInput.getFormDataMap();
			List<InputPart> fileParts = uploadForm.get("uploadFile");
			String appName = FormUtil.getFormString(uploadForm.get("appName"));
			String isGreyUpdate = FormUtil.getFormString(uploadForm.get("isGrayUpdating"));
			if (fileParts != null && !fileParts.isEmpty()) {
				InputPart inputPart = fileParts.get(0);
				InputStream inputStream = inputPart.getBody(InputStream.class, null);
				file = new File(appName);
				FormUtil.inputstreamtofile(inputStream, file);
			}
			if ("true".equals(isGreyUpdate)) {
				String appRawName = null;
				String num = null;
				String newAppName = null;
				if (appName.indexOf('-') >= 0) {
					appRawName = appName.substring(0, appName.indexOf('-'));
					num = appName.substring(appName.indexOf('-') + 1, appName.length());
				}
				if (appRawName != null && num != null) {
					int version = Integer.valueOf(num) + 1;
					newAppName = appRawName + "-" + String.valueOf(version);
				} else {
					newAppName = appName + "-" + "2";
				}

				CfAppExample caE = new CfAppExample();
				caE.createCriteria().andAppNameEqualTo(appName)
						.andOrgEqualTo((String) session.getAttribute(LoginHandler.ORG))
						.andSpaceEqualTo((String) session.getAttribute(LoginHandler.SPACE));
				List<CfApp> appDbs = caMapper.selectByExample(caE);
				CfApp appDb = null;
				if (appDbs != null && !appDbs.isEmpty()) {
					appDb = appDbs.get(0);
					appDb.setRelatedApp(newAppName);
					caMapper.updateByPrimaryKeySelective(appDb);
				}
				AppTemplate tpl = atlMapper.selectByPrimaryKey(appDb.getTemplateId()); // get
																						// domain
				String domain = tpl.getDomain();
				List<String> uri = new ArrayList<String>();
				uri.add(appName + "." + domain);
				Map<String, Object> params = new HashMap<String, Object>();
				Map<String, Object> appCl = ApplicationApi.getApp(appDb.getUuid(), session);
				List<String> services = new ArrayList<String>();

				if (appCl != null) {
					List<Map<String, Object>> servicesRes = (List<Map<String, Object>>) appCl.get("services");

					for (Map<String, Object> sRes : servicesRes) {
						services.add((String) sRes.get("name"));
					}
					params.put("name", newAppName);
					params.put("memory", appCl.get("memory"));
					params.put("instances", appCl.get("instances"));
					params.put("space_guid", UserApi.get_space_id(session, appDb.getOrg(), appDb.getSpace()));
					params.put("buildpack", appCl.get("buildpack"));
					params.put("disk_quota", 1024);
				}

				String appUuid = ApplicationApi.createApplication(params, session);
				CfApp cfApp = new CfApp(newAppName, Integer.valueOf(appDb.getEnvId()), appDb.getOrg(), appDb.getSpace(),
						appDb.getTemplateId(), appUuid);
				cfApp.setRelatedApp(appName);

				caMapper.insertSelective(cfApp);
				ApplicationApi.updateApplicationUrls(appUuid, appDb.getOrg(), appDb.getSpace(), uri, session);
				ApplicationApi.uploadAppBit(cfApp, file, session);

				Integer appId = cfApp.getId();
				getAppPatterns(appId);

				if (services != null) {
					for (String service : services) {
						if (service.startsWith("log")) {
							String msg = " get patterns [GP] appid:" + appUuid;
							lognodeClient.notify((msg.length() - 1) + msg);
							ApplicationApi.bindService(appUuid, service, session);
						}
					}
				}
				ApplicationApi.startApplication(appUuid, session);

			} else {
				CfAppExample caExample = new CfAppExample();
				caExample.createCriteria().andAppNameEqualTo(appName);
				CfApp ca = caMapper.selectByExample(caExample).get(0);
				ApplicationApi.uploadAppBit(ca, file, session);
				ApplicationApi.restartApplication(ca.getUuid(), session);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (file != null) {
				file.deleteOnExit();
			}
		}
		return ExtJSResponse.successRes();
	}

	private void getAppPatterns(int appId) {
		AppLogPatternsExample appLogPatternsExample = new AppLogPatternsExample();
		appLogPatternsExample.createCriteria().andAppIdEqualTo(appId);
		List<AppLogPatterns> patternIds = alpMapper.selectByExample(appLogPatternsExample);
		List<String> patternKeys = new ArrayList<String>();
		List<String> patterns = new ArrayList<String>();
		boolean error = true;
		boolean exception = true;
		try {
			for (int i = 0; i < patternIds.size(); i++) {
				LogPatternExample example = new LogPatternExample();
				example.createCriteria().andPatternIdEqualTo(patternIds.get(i).getAppPattern());
				List<LogPattern> lp = lpMapper.selectByExample(example);
				error = lp.get(0).getPatternName().equals("Error");
				exception = lp.get(0).getPatternName().equals("Exception");
				patternKeys.add(lp.get(0).getPatternName());
				patterns.add(lp.get(0).getPattern());
			}

			insert(error, exception, patternKeys, patterns, appId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * add parameter of service of Oracle
	 * 
	 * @param om
	 * @param msm
	 * @param appSources
	 * @param services
	 * @param appUUID
	 * @throws Exception
	 */
	private void addOracleServiceParam(boolean om, boolean msm, List<String> appSources, List<String> services,
			String appUUID) throws Exception {
		if (appSources == null) {
			return;
		}
		Map<String, String> env = ApplicationApi.getAppEnv(appUUID, session);
		for (int i = 0; i < appSources.size(); i++) {
			if (om && services.get(i).startsWith("Oracle")) {
				env.put(appSources.get(i), services.get(i));
			} else if (msm && services.get(i).startsWith("MySQL")) {
				env.put(appSources.get(i), services.get(i));
			}

		}
		ApplicationApi.updateApplicationEnv(appUUID, env, session);

	}

	/**
	 * bind service by reflect
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public ExtJSResponse bindServiceByReflect(Map<String, Object> params) throws NoSuchMethodException,
			SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class clazz = this.getClass();
		Method method = clazz.getDeclaredMethod("bindOracleService2", Map.class);
		method.invoke(this, params);
		return null;
	}

	/**
	 * bind service of Oracle
	 * 
	 * @param params
	 */
	@SuppressWarnings("unchecked")
	private void bindOracleService2(Map<String, Object> params) {
		List<String> appSource = (List<String>) params.get("appSource");
	}

	/**
	 * bind service of oracle
	 * 
	 * @param appSources
	 * @param appServices
	 * @param isMapping
	 * @param appName
	 * @return
	 * @throws Exception
	 */
	@Path("/bindOracleService")
	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public ExtJSResponse bindOracleService(@FormParam("appSource") String[] appSources,
			@FormParam("service") String[] appServices, @FormParam("oracleMapping") String isOracleMapping,
			@FormParam("mysqlMapping") String isMysqlMapping, @FormParam("appName") String appName) throws Exception {
		List<String> repeat = new ArrayList<>();
		List<String> appSource = CollectionUtils.arrayToList(appSources);
		List<String> services = CollectionUtils.arrayToList(appServices);
		CfAppExample caExample = new CfAppExample();
		caExample.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caExample).get(0);
		List<String> appService = ApplicationApi.getAllAppServiceName(ca.getUuid(), session);
		if (appService != null && appService.size() != 0) {
			for (String service : services) {
				if (appService.contains(service)) {
					repeat.add(service);
				}
			}
		}

		if (repeat.size() != 0) {
			return ExtJSResponse.errorResWithDate(repeat);
		}

		addOracleServiceParam(Boolean.valueOf(isOracleMapping), Boolean.valueOf(isMysqlMapping), appSource, services,
				ca.getUuid());
		for (String service : services) {
			ApplicationApi.bindService(ca.getUuid(), service, session);
		}
		return ExtJSResponse.successRes();
	}

	/**
	 * lmx - 未完成：可能要改变session中的TOKEN maybe duplicated as need is changed 切换org，
	 * space
	 * 
	 * @param orgName
	 * @param spaceName
	 * @return
	 */
	@SuppressWarnings("unused")
	/*
	 * private CloudFoundryClient changeClient(String orgName, String spaceName)
	 * { try { String username = (String) session
	 * .getAttribute(LoginHandler.USERNAME); String password = (String) session
	 * .getAttribute(LoginHandler.PASSWORD); URL target = (URL)
	 * session.getAttribute(LoginHandler.TARGET); CloudCredentials credentials =
	 * new CloudCredentials(username, password); CloudFoundryClient client = new
	 * CloudFoundryClient(credentials, target, orgName, spaceName);
	 * CfUserExample cuEx = new CfUserExample();
	 * cuEx.createCriteria().andUserNameEqualTo(username); //
	 * .andUserPassEqualTo(password); CfUser user =
	 * cuMapper.selectByExample(cuEx).get(0); user.setLastOrg(orgName);
	 * user.setLastSpace(spaceName); cuMapper.updateByPrimaryKey(user);
	 * session.setAttribute(LoginHandler.CLIENT, client); return client; } catch
	 * (Exception e) { logger.error(e); return null; } }
	 */
	/**
	 * download a example application
	 * 
	 * @param appName
	 * @param response
	 *            ，<b>do not set the param</b>
	 * @return
	 * @throws Exception
	 */
	@Path("/download")
	public ExtJSResponse downloadApp(@QueryParam("appName") final String appName, @Context HttpServletResponse response)
			throws Exception {
		return null;
		/*
		 * OutputStream outputStream = null; try { CloudFoundryClient client =
		 * (CloudFoundryClient) session .getAttribute(LoginHandler.CLIENT);
		 * response.reset(); String fileName = "attachment;filename=\"" +
		 * getRandomName(5) + "\";"; response.setHeader("Content-disposition",
		 * fileName); response.setContentType(
		 * "application/OCTET-STREAM; charset=" + "UTF-8"); outputStream =
		 * response.getOutputStream(); String file = client.getFile(appName, 0,
		 * null); outputStream.write(file.getBytes()); outputStream.flush();
		 * return ExtJSResponse.successRes(); } finally { if (outputStream !=
		 * null) { outputStream.close(); } }
		 */
	}

	/**
	 * get all info about buildpack
	 * 
	 * @return
	 * @throws Exception
	 */
	/*
	 * @Path("/getBuildPack")
	 * 
	 * @GET public ExtJSResponse getEnvOfApp() throws Exception { Map<String,
	 * Object> data = null; data = ApplicationApi.getBuildPacks(session); return
	 * ExtJSResponse.successResWithData(data); }
	 */

	// *************** env operations of application : [get,add,delete]

	/**
	 * get all env of an application by appName
	 * 
	 * @param appName
	 * @return
	 * @throws Exception
	 */
	@Path("/getEnv")
	@GET
	public ExtJSResponse getEnvOfAll(@QueryParam("appName") final String appName) throws Exception {
		List<AppManagement.Evn> envs = new ArrayList<AppManagement.Evn>();
		CfAppExample caExample = new CfAppExample();
		caExample.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caExample).get(0);
		Map<String, String> envMap = ApplicationApi.getAppEnv(ca.getUuid(), session);
		for (Entry<String, String> entry : envMap.entrySet()) {
			envs.add(new Evn(entry.getKey(), entry.getValue()));
		}
		return ExtJSResponse.successResWithData(envs);
	}

	/**
	 * add an env of an application by appName, and key of env , value of env
	 * 
	 * @param appName
	 * @param key
	 * @param value
	 * @return
	 * @throws Exception
	 */
	@Path("/addEnv")
	@GET
	public ExtJSResponse addEnvOfApp(@QueryParam("appName") final String appName, @QueryParam("key") final String key,
			@QueryParam("value") final String value) throws Exception {
		CfAppExample caExample = new CfAppExample();
		caExample.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caExample).get(0);
		Map<String, String> env = ApplicationApi.getAppEnv(ca.getUuid(), session);
		env.put(key, value);
		ApplicationApi.updateApplicationEnv(ca.getUuid(), env, session);
		return ExtJSResponse.successRes();
	}

	/**
	 * delete an env of an application by appName and key of the env
	 * 
	 * @param appName
	 * @param key
	 * @return
	 * @throws Exception
	 */
	@Path("/deleteEnv")
	@GET
	public ExtJSResponse setEnvOfApp(@QueryParam("appName") final String appName, @QueryParam("key") final String key)
			throws Exception {
		CfAppExample caExample = new CfAppExample();
		caExample.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caExample).get(0);
		Map<String, String> env = ApplicationApi.getAppEnv(ca.getUuid(), session);
		env.remove(key);
		ApplicationApi.updateApplicationEnv(ca.getUuid(), env, session);
		return ExtJSResponse.successRes();
	}

	/**
	 * Change <b>oldKey</b> env to <b>newKey</b> with value of <b>value</b>
	 * example
	 * 
	 * @param appName
	 * @param oldKey
	 * @param newKey
	 * @param value
	 * @return
	 * @throws Exception
	 */
	@Path("/modifyEnv")
	@GET
	public ExtJSResponse modifyEnvOfApp(@QueryParam("appName") final String appName,
			@QueryParam("oldKey") final String oldKey, @QueryParam("newKey") final String newKey,
			@QueryParam("value") final String value) throws Exception {
		CfAppExample caExample = new CfAppExample();
		caExample.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caExample).get(0);
		Map<String, String> envMap = ApplicationApi.getAppEnv(ca.getUuid(), session);
		if (oldKey != null) {
			envMap.remove(oldKey);
		}
		envMap.put(newKey, value);
		ApplicationApi.updateApplicationEnv(ca.getUuid(), envMap, session);
		return ExtJSResponse.successRes();
	}

	// *************** monitor application
	/**
	 * monitor application instance by appName and index of instance
	 * 
	 * @param appName
	 * @param index
	 * @return
	 * @throws IOException
	 */
	@Path("/monitor")
	@GET
	public ExtJSResponse monitApp(@QueryParam("appName") final String appName, @QueryParam("index") final int index)
			throws Exception {
		Map<String, Object> data = null;
		if (appName != null) {
			CfAppExample caExample = new CfAppExample();
			caExample.createCriteria().andAppNameEqualTo(appName);
			CfApp ca = caMapper.selectByExample(caExample).get(0);
			// 获取数据的同时进行自动扩展
			data = ApplicationApi.monitApp(session, ca.getUuid(), index, ca.getAutoscale(), ca.getMaxCpu(),
					ca.getMinCpu(), ca.getMaxInstance(), ca.getMinInstance());
		}
		return ExtJSResponse.successResWithMap(data);

	}

	// *************** service operations of application

	/**
	 * bind service to application
	 * 
	 * @param appName
	 * @param serviceName
	 * @return
	 * @throws Exception
	 */
	@Path("/bindService")
	@GET
	public ExtJSResponse bingService(@QueryParam("appName") final String appName,
			@QueryParam("serviceName") final String serviceName, @QueryParam("data") final ArrayList<String> data)
					throws Exception {
		CfAppExample caExample = new CfAppExample();
		caExample.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caExample).get(0);
		if ("logservice".equals(serviceName.toLowerCase())) {
			boolean error = data.contains("Error");
			boolean exception = data.contains("Exception");
			if (error) {
				data.remove("Error");
			}
			if (exception) {
				data.remove("Exception");
			}
			List<String> patternKeys = new ArrayList<>();
			List<String> patterns = new ArrayList<>();

			for (String pattern : data) {
				if (!"".equals(pattern) && pattern != null) {
					int index = pattern.indexOf(":");
					patternKeys.add(pattern.substring(0, index));
					patterns.add(pattern.substring(index + 1, pattern.length()));
				}
			}
			String checkPmsg = checkPattern(patternKeys);
			if (checkPmsg != null && !"".equals(checkPmsg) && !"success".equals(checkPmsg)) {
				ExtJSResponse response = ExtJSResponse.errorRes();
				response.put("source", "patternExist");
				response.put("error", checkPmsg);
				return response;
			}
			int appId = ca.getId();
			insert(error, exception, patternKeys, patterns, appId);
			String msg = " get patterns [GP] appid:" + ca.getUuid();
			lognodeClient.notify((msg.length() - 1) + msg);
			ApplicationApi.bindService(ca.getUuid(), serviceName, session);
		} else {
			ApplicationApi.bindService(ca.getUuid(), serviceName, session);
		}
		/*
		 * if(serviceName.toLowerCase().equals("oracle")){
		 * client.bindService(appName, serviceName); }
		 */
		return ExtJSResponse.successResWithData(data);
	}

	/**
	 * unbind service form application
	 * 
	 * @param appName
	 * @param serviceName
	 * @return
	 * @throws Exception
	 */
	@Path("/unbindService")
	@GET
	public ExtJSResponse unbindService(@QueryParam("appName") final String appName,
			@QueryParam("serviceName") final String serviceName) throws Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		ApplicationApi.unbindService(ca.getUuid(), serviceName, session);
		Map<String, String> envMap = ApplicationApi.getAppEnv(ca.getUuid(), session);
		Map<String, String> env = new HashMap<>();
		env.putAll(envMap);
		for (Entry<String, String> entry : envMap.entrySet()) {
			if ((entry.getValue().equals(serviceName))) {
				env.remove(entry.getKey());
			}
		}
		ApplicationApi.updateApplicationEnv(ca.getUuid(), env, session);
		if ("logservice".equals(serviceName.toLowerCase())) {
			int appid = ca.getId();
			AppLogPatternsExample alpEx = new AppLogPatternsExample();
			alpEx.createCriteria().andAppIdEqualTo(appid);
			List<AppLogPatterns> alpList = alpMapper.selectByExample(alpEx);
			for (AppLogPatterns alp : alpList) {
				if (alp.getAppPattern() != 1 && alp.getAppPattern() != 2) {
					int patternId = alp.getAppPattern();
					lpMapper.deleteByPrimaryKey(patternId);
					PatternFieldExample pfEx = new PatternFieldExample();
					pfEx.createCriteria().andPatternIdEqualTo(patternId);
					patternFieldMapper.deleteByExample(pfEx);
				}
			}
			alpMapper.deleteByExample(alpEx);
			String msg = " remove patterns [RP] appid:" + ca.getUuid();
			lognodeClient.notify((msg.length() - 1) + msg);
		}
		return ExtJSResponse.successRes();
	}

	// *************** operations of application :
	// [start,stop,restart,update,delete,details]

	/**
	 * stop an application by name
	 * 
	 * @param appName
	 * @return
	 * @throws Exception
	 */
	@Path("/stop")
	@GET
	public ExtJSResponse stop(@QueryParam("appName") final String appName) throws Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		ApplicationApi.stopApplication(ca.getUuid(), session);
		return ExtJSResponse.successRes();
	}

	/**
	 * update disk quota of application,更新硬盘限额
	 * 
	 * @param appName
	 * @param disk
	 * @return
	 * @throws Exception
	 */
	@Path("/updateDisk")
	@GET
	public ExtJSResponse updateDisk(@QueryParam("appName") final String appName, @QueryParam("disk") final int disk)
			throws Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		ApplicationApi.updateApplicationMem(ca.getUuid(), disk, session);
		return ExtJSResponse.successRes();
	}

	/**
	 * update domains of application
	 * 
	 * @param appName
	 * @param domains
	 *            domains should be separated by ","
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@Path("/updateDomain")
	@GET
	public ExtJSResponse updataDomain(@QueryParam("appName") final String appName,
			@QueryParam("domains") final String domains) throws Exception {
		if (domains != null && !"".equals(domains)) {
			CfAppExample caEx = new CfAppExample();
			caEx.createCriteria().andAppNameEqualTo(appName);
			CfApp ca = caMapper.selectByExample(caEx).get(0);
			List<String> uris = CollectionUtils.arrayToList(domains.split(","));
			ApplicationApi.updateApplicationUrls(ca.getUuid(), ca.getOrg(), ca.getSpace(), uris, session);
		}
		return ExtJSResponse.successRes();

	}

	/**
	 * update the instances number of application
	 * 
	 * @param appName
	 * @param instances
	 * @return
	 * @throws Exception
	 */
	@Path("/updateInstNum")
	@GET
	public ExtJSResponse updateInstNum(@QueryParam("appName") final String appName,
			@QueryParam("instanceNum") final int instances) throws Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		ApplicationApi.updateApplicationInstance(ca.getUuid(), instances, session);
		return ExtJSResponse.successRes();
	}

	/**
	 * update memory of application
	 * 
	 * @param appName
	 * @param memory
	 * @return
	 * @throws Exception
	 */
	@Path("/updateMemoryNum")
	@GET
	public ExtJSResponse updateMemoryNum(@QueryParam("appName") final String appName,
			@QueryParam("memoryNum") final int memory) throws Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		ApplicationApi.updateApplicationMem(ca.getUuid(), memory, session);
		return ExtJSResponse.successRes();
	}

	/**
	 * scale instance, CPU and memory of an application
	 * 
	 * @param appName
	 * @param memory
	 * @param instanceNum
	 * @param minCpu
	 * @param maxCpu
	 * @param minInstance
	 * @param maxInstance
	 * @param autoScale
	 * @return
	 * @throws Exception,
	 *             NumberFormatException
	 */
	@Path("/scaleApp")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@POST
	public ExtJSResponse updateInstanceOrMem(@FormParam("appName") final String appName,
			@FormParam("memoryNum") final String memory, @FormParam("instanceNum") final String instances,
			@FormParam("minCpu") final String minCpu, @FormParam("maxCpu") final String maxCpu,
			@FormParam("minInstance") final String minInstance, @FormParam("maxInstance") final String maxInstance,
			@FormParam("autoScale") final Boolean auto) throws NumberFormatException, Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		if (!auto) {
			if (StringUtil.isNotEmpty(instances)) {
				ApplicationApi.updateApplicationInstance(ca.getUuid(), Integer.valueOf(instances), session);
			}

			if (StringUtil.isNotEmpty(memory)) {
				ApplicationApi.updateApplicationMem(ca.getUuid(), (int) (Float.valueOf(memory) * 1024), session);
			}

			CfAppExample example = new CfAppExample();
			example.createCriteria().andAppNameEqualTo(appName);
			CfApp app = new CfApp();
			app.setAutoscale((short) 0);
			caMapper.updateByExampleSelective(app, example);
		} else {
			if (StringUtil.isNotEmpty(minCpu) && StringUtil.isNotEmpty(maxCpu)) {
				CfAppExample example = new CfAppExample();
				example.createCriteria().andAppNameEqualTo(appName);
				CfApp app = new CfApp();
				app.setMinCpu(Double.valueOf(minCpu));
				app.setMaxCpu(Double.valueOf(maxCpu));
				app.setAutoscale((short) 1);
				caMapper.updateByExampleSelective(app, example);
				app = null;
				example = null;
			}

			if (StringUtil.isNotEmpty(minInstance) && StringUtil.isNotEmpty(maxInstance)) {
				CfAppExample example = new CfAppExample();
				example.createCriteria().andAppNameEqualTo(appName);
				CfApp app = new CfApp();
				app.setMinInstance(Integer.valueOf(minInstance));
				app.setMaxInstance(Integer.valueOf(maxInstance));
				app.setAutoscale((short) 1);
				caMapper.updateByExampleSelective(app, example);
				app = null;
				example = null;
			}
		}
		return ExtJSResponse.successRes();
	}

	/**
	 * delete an application by name
	 * 
	 * @param appName
	 * @return
	 * @throws Exception
	 */
	@Path("/delete")
	@GET
	public ExtJSResponse delete(@QueryParam("appName") final String appName) throws Exception {
		CfAppExample caE = new CfAppExample();
		caE.createCriteria().andAppNameEqualTo(appName);
		CfApp app = caMapper.selectByExample(caE).get(0);
		ApplicationApi.deleteApp(app.getUuid(), session);
		Integer appId = app.getId();
		caMapper.deleteByExample(caE);
		String msg = " remove patterns [RP] appid:" + app.getUuid();
		lognodeClient.notify((msg.length() - 1) + msg);
		AppLogConfigExample alcEx = new AppLogConfigExample();
		alcEx.createCriteria().andAppIdEqualTo(appId);
		alcMapper.deleteByExample(alcEx);

		CfAppExample caExam = new CfAppExample();
		caExam.createCriteria().andRelatedAppEqualTo(appName);
		List<CfApp> rapps = caMapper.selectByExample(caExam);
		if (rapps != null && !rapps.isEmpty()) {
			for (int i = 0; i < rapps.size(); i++) {
				CfApp cfapp = rapps.get(i);
				cfapp.setRelatedApp("");
				caMapper.updateByPrimaryKeySelective(cfapp);
			}
		}

		AppLogPatternsExample alpEx = new AppLogPatternsExample();
		alpEx.createCriteria().andAppIdEqualTo(appId);
		List<AppLogPatterns> list = alpMapper.selectByExample(alpEx);
		for (AppLogPatterns alp : list) {
			if (alp.getAppPattern() != 1 && alp.getAppPattern() != 2) {
				int patternId = alp.getAppPattern();
				lpMapper.deleteByPrimaryKey(patternId);
				PatternFieldExample pfEx = new PatternFieldExample();
				pfEx.createCriteria().andPatternIdEqualTo(patternId);
				patternFieldMapper.deleteByExample(pfEx);
			}

		}
		alpMapper.deleteByExample(alpEx);
		lm.deleteLog(appName);

		return ExtJSResponse.successRes();
	}

	/**
	 * boot an application by name
	 * 
	 * @param appName
	 * @return
	 * @throws Exception
	 */
	@Path("/boot")
	@GET
	public ExtJSResponse start(@QueryParam("appName") final String appName) throws Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		ApplicationApi.startApplication(ca.getUuid(), session);
		return ExtJSResponse.successRes();
	}

	/**
	 * reboot an application by name
	 * 
	 * @param appName
	 * @return
	 * @throws Exception
	 */
	@Path("/reboot")
	@GET
	public ExtJSResponse restart(@QueryParam("appName") final String appName) throws Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		CfApp ca = caMapper.selectByExample(caEx).get(0);
		ApplicationApi.restartApplication(ca.getUuid(), session);
		return ExtJSResponse.successRes();
	}

	/**
	 * get details of application by
	 * appName,修改了方法，在查找app的时候只提供appName进行查看即可，不需要通过org和space名字
	 * 
	 * @param appName
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@Path("/details")
	@GET
	public ExtJSResponse detail(@QueryParam("appName") final String appName) throws Exception {
		Map<String, Object> resMap = null;
		resMap = new HashMap<String, Object>();
		Map<String, Integer> insStaMap = new HashMap<String, Integer>();
		CfAppExample caE = new CfAppExample();
		caE.createCriteria().andAppNameEqualTo(appName);
		List<CfApp> appDbs = caMapper.selectByExample(caE);
		CfApp appDb = null;
		if (appDbs != null && !appDbs.isEmpty()) {
			appDb = appDbs.get(0);
		}
		AppTemplate tpl = atlMapper.selectByPrimaryKey(appDb.getTemplateId());

		resMap.put("title", appName);
		List<String> domains = ApplicationApi.getAppRoutesList(appDb.getUuid(), session);
		resMap.put("domain", domains);
		if (tpl != null) {
			resMap.put("itemColor", tpl.getTemColor());
			resMap.put("itemImg", tpl.getTemImg());
		}
		Map<String, Object> appCl = ApplicationApi.getApp(appDb.getUuid(), session);
		if (appCl != null) {
			List<Map<String, Object>> servicesRes = (List<Map<String, Object>>) appCl.get("services");
			List<String> services = new ArrayList<String>();
			for (Map<String, Object> sRes : servicesRes) {
				services.add((String) sRes.get("name"));
			}
			int instNum = (int) appCl.get("instances");
			resMap.put("max_instance", appDb.getMaxInstance());
			resMap.put("min_instance", appDb.getMinInstance());
			resMap.put("runtime", appCl.get("buildpack"));
			resMap.put("instance", instNum);
			resMap.put("memory", (Integer) (appCl.get("memory")) / 1024.0);
			resMap.put("space", appCl.get("disk_quota"));
			resMap.put("serviceName", services);
			resMap.put("status", appCl.get("state"));
			resMap.put("max_cpu", appDb.getMaxCpu());
			resMap.put("min_cpu", appDb.getMinCpu());
			resMap.put("max_instance", appDb.getMaxInstance());
			resMap.put("min_instance", appDb.getMinInstance());
			resMap.put("autoScale", appDb.getAutoscale() == 1 ? true : false);

			int[] statusCount = new int[6];
			boolean stateFlag = false;
			List<String> instStatus = new ArrayList<String>();
			if ("STARTED".equals(appCl.get("state"))) { // app is running
				Map<String, Object> states = ApplicationApi.getAppInstances(appDb.getUuid(), session);
				if (states != null) {
					for (int i = 0; i < instNum; i++) {
						if (states.get(String.valueOf(i)) == null) {
							statusCount[InstanceState.valueOfWithDefault("DOWN").ordinal()]++;
							instStatus.add("DOWN");
						} else {
							String state = (String) ((Map<String, Object>) states.get(String.valueOf(i))).get("state");
							statusCount[InstanceState.valueOfWithDefault(state).ordinal()]++;
							instStatus.add(state);
						}

					}
				} else {
					stateFlag = true;
				}

			} else { // app is not running
				stateFlag = true;
			}

			if (stateFlag) {
				for (int i = 0; i < instNum; i++) {
					instStatus.add("DOWN");
				}
				statusCount[0] = instNum;
			}
			for (InstanceState e : InstanceState.values()) {
				insStaMap.put(e.toString(), statusCount[e.ordinal()]);
			}
			resMap.put("instStatus", instStatus);

			resMap.put("instanceStatus", insStaMap);

		}
		resMap.put("message", lm.listApp(appName)); // 这个先写死，等待日至接口完成
		return ExtJSResponse.successResWithMap(resMap);
	}

	/***
	 * check whether the appName already exits
	 * 
	 * @param appName
	 * @return
	 * @throws Exception
	 */
	@Path("/checkAppName")
	@GET
	public ExtJSResponse checkAppName(@QueryParam("appName") final String appName,
			@QueryParam("orgName") final String orgName, @QueryParam("spaceName") final String spaceName)
					throws Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		List<CfApp> apps = caMapper.selectByExample(caEx);
		if (apps != null && apps.size() > 0) {
			return ExtJSResponse.successResWithData(false);
		}
		if (ApplicationApi.getParticularApplicationBySpace(session, orgName, spaceName, appName) != null) {
			return ExtJSResponse.successResWithData(false);
		}
		return ExtJSResponse.successResWithData(true);

	}

	// *********************** Yufang Jiang **************************

	private void insert(boolean error, boolean exception, final List<String> patternKeys, final List<String> patterns,
			final Integer appId) throws Exception {
		ExtendedGrok grok = new ExtendedGrok();
		grok.addPatternFromFile(classLoader.getResource("patterns/grok-patterns").getPath());
		grok.addPatternFromFile(classLoader.getResource("patterns/local-patterns").getPath());
		LogPatternExample example = null;

		LogPattern lp = null;
		AppLogPatterns alp = null;
		PatternField patternField = null;
		example = new LogPatternExample();
		if (error) {

			example.createCriteria().andPatternNameEqualTo("ERROR");
			lp = lpMapper.selectByExample(example).get(0);
			alp = new AppLogPatterns();
			alp.setAppId(appId);
			alp.setAppPattern(lp.getPatternId());
			alpMapper.insertSelective(alp);
		}
		example.clear();
		if (exception) {
			example.createCriteria().andPatternNameEqualTo("EXCEPTION");
			lp = lpMapper.selectByExample(example).get(0);
			alp = new AppLogPatterns();
			alp.setAppId(appId);
			alp.setAppPattern(lp.getPatternId());
			alpMapper.insertSelective(alp);
		}

		if (patternKeys == null) {
			return;
		}
		for (int i = 0; i < patternKeys.size(); i++) {
			lp = new LogPattern();
			lp.setPatternName(patternKeys.get(i));
			lp.setPattern(patterns.get(i));
			lpMapper.insertSelective(lp);
			alp = new AppLogPatterns();
			alp.setAppId(appId);
			alp.setAppPattern(lp.getPatternId());
			alpMapper.insertSelective(alp);
			for (String field : grok.getPatternField(patterns.get(i))) {
				patternField = new PatternField();
				patternField.setPatternField(field);
				patternField.setPatternId(lp.getPatternId());
				patternFieldMapper.insertSelective(patternField);
			}
		}
	}

	/**
	 * check the keys of pattern
	 * 
	 * @param patternKeys
	 * @return
	 * @throws Exception
	 */
	private String checkPattern(final List<String> patternKeys) throws Exception {
		if (patternKeys == null || patternKeys.size() == 0) {
			return "success";
		}
		StringBuffer errorMsg = new StringBuffer();
		LogPatternExample example = new LogPatternExample();
		example.createCriteria().andPatternNameIn(patternKeys);
		List<LogPattern> lpatterns = lpMapper.selectByExample(example);
		for (LogPattern pattern : lpatterns) {
			errorMsg.append(pattern.getPatternName());
			errorMsg.append(",");
		}
		if (!StringUtils.isEmpty(errorMsg.toString())) {
			String exist = errorMsg.toString();
			if (exist.endsWith(",")) {
				exist = exist.substring(0, exist.length() - 1);
			}
			return exist;
		}
		return "success";
	}

	/**
	 * get events of an application
	 * 
	 * @param appName
	 * @return
	 * @throws Exception
	 */
	@GET
	@Path("/events")
	public ExtJSResponse getAppEvents(@QueryParam("appName") final String appName) throws Exception {
		CfAppExample caEx = new CfAppExample();
		caEx.createCriteria().andAppNameEqualTo(appName);
		List<CfApp> apps = caMapper.selectByExample(caEx);
		CfApp app = null;
		if (apps != null && apps.size() > 0) {
			app = apps.get(0);
		}
		List<Map<String, Object>> events = ApplicationApi.getAppEventList(app.getUuid(), session);
		return ExtJSResponse.successResWithData(events);
	}

	/**
	 * a class work as a map
	 * 
	 * @author lmx
	 * 
	 */
	public class Evn {
		private String key;
		private String value;

		Evn(String key, String value) {
			this.key = key;
			this.value = value;
		}

		public String getKey() {
			return key;
		}

		public void setKey(String key) {
			this.key = key;
		}

		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}
	}

	public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		// AppManagement app = new AppManagement();
		// Map<String, Object> params = new HashMap<>();
		// params.put("appSource", new ArrayList<String>());
		// app.bindServiceByReflect(params);
		String v = "VCAP_APPLICATION={\"limits\":{\"mem\":1024,\"disk\":1024,\"fds\":16384},\"application_version\":\"196eba9b-fc57-442f-98bf-f03379aadbd6=3\",\"application_name\":\"mysqlbroker=3\",\"application_uris\":[\"mysqlbroker.local.lai\"]";
		String[] pARMStrings = v.split("=", 2);
		for (String P : pARMStrings) {
			System.out.println(P);
		}
	}
}
